package org.viva.action.wx;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.viva.core.Log;
import org.viva.core.api.SkyEye;
import org.viva.service.wx.WeiXinAuthService;

public class MpAction {

    WeiXinAuthService wxas = new WeiXinAuthService();

    @RequestMapping(value = "/wx/mp")
    @ResponseBody
    public String index() {

        HttpServletRequest request = SkyEye.getRequest();
        String msg_signature = request.getParameter("msg_signature");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        boolean isok = false; // 开发者认证成功？
        try {
            isok = this.wxas.checkSignature(signature, timestamp, nonce, msg_signature, request.getInputStream());
            // this.menuServ.initThreadMenuList(false); // 测试问题
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Log.debug(" 微信环境认证 : " + isok);

        if (isok) {
            if (StringUtils.isBlank(echostr)) {
                Map<String, Object> userInfo = this.wxas.getUserInfo();
                if (userInfo.isEmpty() || userInfo.containsKey("errmsg")) {
                    String msg = userInfo.isEmpty() ? "获取用户信息出错" : userInfo.get("errmsg").toString();
                    // echostr = this.msgServ.response(msg);
                } else {
                    String newuser = (String) userInfo.get("newuser");
                    // if (StringUtils.isNotBlank(newuser)) {
                    // echostr =
                    // this.msgServ.response("hi，欢迎新用户，\n请输入【bind
                    // 身份证或营业执照】来绑定您的微信号与我们的系统。\n如不清楚请联系客服。");
                    // } else {
                    // echostr = this.msgServ.response();
                    // }
                    // send message
                    // this.msgServ.sendMsg("你好");
                }
            }
            return "";
        }
        return "";

    }
}
